package com.nuorui.module.system.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.nuorui.common.constant.AdminCacheConst;
import com.nuorui.common.core.enums.UserTypeEnum;
import com.nuorui.common.core.domain.LoginUser;
import com.nuorui.module.system.domain.entity.DepartmentEntity;
import com.nuorui.module.system.domain.entity.UserEntity;
import com.nuorui.module.system.domain.vo.MenuVO;
import com.nuorui.module.system.domain.vo.RoleVO;
import com.nuorui.module.system.domain.vo.UserPermission;
import com.nuorui.module.system.service.DepartmentService;
import com.nuorui.module.system.service.RoleMenuService;
import com.nuorui.module.system.service.RoleUserService;
import com.nuorui.module.system.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类描述
 *
 * @author: Fred
 * @email 453086@qq.com
 * @create: 2025-06-09 09:12
 */
@Slf4j
@Service
@AllArgsConstructor
public class LoginManager {

    private final UserService userService;
    private final DepartmentService departmentService;
    private final RoleUserService roleUserService;
    private final RoleMenuService roleMenuService;


    /**
     * 获取请求用户信息
     */
//    @Cacheable(AdminCacheConst.Login.REQUEST_EMPLOYEE)
    public LoginUser getRequestEmployee(Long requestUserId) {
        if (requestUserId == null) {
            return null;
        }

        UserEntity userEntity = userService.getById(requestUserId);
        if (userEntity == null) {
            return null;
        }
        return loadLoginInfo(userEntity);
    }

    /**
     * 获取登录的用户信息
     */
//    @CachePut(value = AdminCacheConst.Login.REQUEST_EMPLOYEE, key = "#userEntity.userId")
    public LoginUser loadLoginInfo(UserEntity userEntity) {
        if (userEntity == null) {
            return null;
        }
        // 基础信息
        LoginUser loginUser = BeanUtil.copyProperties(userEntity, LoginUser.class);
        loginUser.setUserType(UserTypeEnum.ADMIN_EMPLOYEE);

        // 部门信息
        DepartmentEntity department = departmentService.getById(userEntity.getDepartmentId());
        loginUser.setDepartmentName(department != null ? department.getDepartmentName() : StrUtil.EMPTY);

        // 头像信息
        return loginUser;
    }

    /**
     * 获取用户的权限（包含 角色列表、权限列表）
     */
    @Cacheable(AdminCacheConst.Login.USER_PERMISSION)
    public UserPermission getUserPermission(Long userId) {
        if(null == userId){
            return null;
        }

        return loadUserPermission(userId);
    }

    /**
     * 获取用户的权限（包含 角色列表、权限列表）
     */
    @CachePut(AdminCacheConst.Login.USER_PERMISSION)
    public UserPermission loadUserPermission(Long userId) {

        UserPermission userPermission = new UserPermission();
        userPermission.setPermissionList(new ArrayList<>());
        userPermission.setRoleList(new ArrayList<>());

        // 角色列表
        List<RoleVO> roleList = roleUserService.getRolesByUserId(userId);
        userPermission.getRoleList().addAll(roleList.stream().map(RoleVO::getRoleCode).collect(Collectors.toSet()));

        // 前端菜单和功能点清单
        UserEntity userEntity = userService.getById(userId);

        List<MenuVO> menuAndPointsList = roleMenuService.getMenusByRoleIdList(roleList.stream().map(RoleVO::getRoleId).collect(Collectors.toList()), userEntity.getIsAdministrator());

        // 权限列表
        HashSet<String> permissionSet = new HashSet<>();
        for (MenuVO menu : menuAndPointsList) {
            if (menu.getPermsType() == null) {
                continue;
            }

            String perms = menu.getApiPerms();
            if (StrUtil.isEmpty(perms)) {
                continue;
            }
            //接口权限
            String[] split = perms.split(StrUtil.COMMA);
            permissionSet.addAll(Arrays.asList(split));
        }
        userPermission.getPermissionList().addAll(permissionSet);

        return userPermission;
    }

    @CacheEvict(value = {AdminCacheConst.Login.USER_PERMISSION, AdminCacheConst.Login.REQUEST_USER}, allEntries = true)
    public void clear(){

    }
}
